<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useIndexStore } from '@/stores/index'

const indexStore = useIndexStore()

onMounted(() => {
  // 预加载
  preload()
})
const router = useRouter()
const count = ref(0)
const percent = ref('')

const preload = () => {
  let chooseEat = import.meta.glob('../assets/img/*', { eager: true })
  let CNEat = import.meta.glob('../assets/img/cn/*', { eager: true })
  let ENEat = import.meta.glob('../assets/img/en/*', { eager: true })
  let allList = { ...chooseEat, ...CNEat, ...ENEat }
  let listlength = Object.keys(allList).length
  for (const item in allList) {
    let image = new Image()
    image.src = allList[item].default
    // console.log(image.src)
    // 图片加载
    image.onload = () => {
      count.value++
      let percentNum = Math.floor((count.value / listlength) * 100)
      percent.value = `${percentNum}%`
    }
    image.onerror = () => {
      console.log('图片加载失败')
    }
  }
}

// 当前是否是pc端
const IsPC = () => {
  var userAgentInfo = navigator.userAgent;
  var Agents = new Array(
    "Android",
    "iPhone",
    "SymbianOS",
    "Windows Phone",
    "iPad",
    "iPod"
  );
  var flag = true;
  for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false;
      break;
    }
  }
  return flag;
}

indexStore.updateDevice(IsPC())

watch(percent, (newVal) => {
  // console.log(newVal)
  if (newVal === '100%') {
    // 默认显示中文
    router.replace('/cn')
  }
})
</script>
<template>
  <div class="loading box clmcenter bg">
    <p>loading...{{ percent }}</p>
  </div>
</template>
<style lang="scss" scoped>
.loading {
  background: #ffffff;
  p {
    color: #000000;
    font-size: 1.5vw;
  }
}
</style>
